package net.zjitc.list;

import net.zjitc.domain.Student;
import net.zjitc.link.Node;

public class MyLinkedList<T> implements MyList<T> {
    private int size;
    private Node<T> first;
    private Node<T> last;

    public MyLinkedList() {
    }

    /**
     * 默认到最后
     *
     * @param data
     * @return
     */
    @Override
    public boolean add(T data) {
        linkLast(data);
        return true;
    }

    private void linkLast(T data) {
        Node<T> node = new Node<>(data);
        if (first == null) {
            first = node;
            last = first;
        } else {
            last.next = node;
            last = last.next;
        }
        size++;
    }

    /**
     * 插入的任意位置
     *
     * @param index
     * @param data
     * @return
     */
    @Override
    public boolean add(int index, T data) {
        if (index < 0 || index > size) {
            throw new RuntimeException("插入的位置越界");
        }
        Node<T> newNode = new Node<>(data);
        if (index == size) { //size==0  加一个判断
            linkLast(data);
            return true;
        }
        if (index == 0) {
            //最前 first
            newNode.next = first;
            first = newNode;
            size++;
            return true;
        }
        //中间
        Node<T> p = first;
        for (int i = 0; i < index - 1; i++) {
            p = p.next;
        }
        newNode.next = p.next;
        p.next = newNode;
        size++;
        return true;
    }

    @Override
    public T remove(T data) {

        return null;
    }

    private void checkWeizhi(int index) {
        if (index<0||index>=size){
            throw new RuntimeException("插入位置越界");
        }
    }

    @Override
    public T remove(int index) {
        checkWeizhi(index);
        Node<T> p=first;
        if (index==0){
            first=p.next;
            p.next=null;
            size--;
            return p.data;
        }
        for (int i=0;i<index-1;i++){
            p=p.next;
        }
        T oldDate=(T)p.next.data;
        p.next=p.next.next;
        if (index==size-1){
            last=p;
        }
        size--;
        return oldDate;
    }

    @Override
    public boolean set(int index, T data) {

        return false;
    }

    @Override
    public T getValue(int index) {

        return null;
    }

    @Override
    public int size() {

        return size;
    }
    public void nizhuan(){
        Node<T> before=null;
        Node<T> p= first;
        Node<T> after=null;
        if (first==null||first.next==null){
            System.out.println("就一个 不需要逆转");

        }else {
            while (p!=null){
                after=p.next;
                p.next=before;
                before=p;
                p=after;
            }
            last=first;
            first=before;
        }

    }
}
